package com.sinosoft.hbzyy.app.wms.base.data.endpoint.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.cxf.message.Message;
import org.apache.cxf.phase.PhaseInterceptorChain;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.MappingJsonFactory;
import org.codehaus.jackson.map.ObjectMapper;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.sinosoft.framework.core.common.exception.BusinessException;
import com.sinosoft.hbzyy.app.weedfs.api.WeedfsService;
import com.sinosoft.hbzyy.app.weedfs.model.RequestResult;
import com.sinosoft.hbzyy.app.wms.base.data.api.AppDictService;
import com.sinosoft.hbzyy.app.wms.base.data.api.OrganizationService;
import com.sinosoft.hbzyy.app.wms.base.data.endpoint.OrganizationEndpoint;
import com.sinosoft.hbzyy.app.wms.base.data.model.AppDictItemEntity;
import com.sinosoft.hbzyy.app.wms.base.data.model.DistrictEntity;
import com.sinosoft.hbzyy.app.wms.base.data.model.OrganizationEntity;
import com.sinosoft.hbzyy.framework.core.api.model.PageList;
import com.sinosoft.hbzyy.framework.util.ResultHelper;

public class OrganizationEndpointImpl implements OrganizationEndpoint {

	private OrganizationService organizationService;

	private WeedfsService weedfsService;

	private AppDictService appDictService;

	private com.sinosoft.framework.core.api.service.OrganizationService organService;

	public com.sinosoft.framework.core.api.service.OrganizationService getOrganService() {
		return organService;
	}

	public void setOrganService(com.sinosoft.framework.core.api.service.OrganizationService organService) {
		this.organService = organService;
	}

	public void setOrganizationService(OrganizationService organizationService) {
		this.organizationService = organizationService;
	}

	public WeedfsService getWeedfsService() {
		return weedfsService;
	}

	public void setWeedfsService(WeedfsService weedfsService) {
		this.weedfsService = weedfsService;
	}

	public OrganizationService getOrganizationService() {
		return organizationService;
	}

	public AppDictService getAppDictService() {
		return appDictService;
	}

	public void setAppDictService(AppDictService appDictService) {
		this.appDictService = appDictService;
	}

	@Override
	public Map<String, Object> createOrganization(OrganizationEntity organ) {
		return organizationService.createOrganization(organ);
	}

	@Override
	public Map<String, Object> createOrganization(String org, String dis) {
		// 将json字符串转换为相应的Entity
		OrganizationEntity organ = null;
		DistrictEntity district = null;
		String id = UUID.randomUUID().toString();
		try {
			MappingJsonFactory factory = new MappingJsonFactory();
			// 解析固定的json格式的字符串
			JsonParser organParser = factory.createJsonParser(org);
			JsonParser disParser = factory.createJsonParser(dis);
			organ = organParser.readValueAs(OrganizationEntity.class);
			district = disParser.readValueAs(DistrictEntity.class);
			organ.setId(id);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		/**
		 * 创建app后台管理机构信息
		 */
		if (!org.equals("{}")) {
			try {
				Message message = PhaseInterceptorChain.getCurrentMessage();
				HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);// 获取到request
				organ.setCreateBy(Long.parseLong(request.getSession().getAttribute("username").toString()));
				organizationService.createOrganization(organ);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			// 创建院区信息
			district.setId(id);
			DistrictEntity districtEntity = organizationService.retrieveDistrictByOrgCodeAndDistictId(
					district.getOrgCode(), district.getDistrictId(), district.getDistrictName());
			if (null != districtEntity) {
				return ResultHelper.buildErrorResult("该机构下已经创建过该院区");
			} else {
				organizationService.createDistrict(district);
			}
		} catch (Exception e) {
			organizationService.deleteOrganizationByOrgCode(organ.getOrgCode());
			return ResultHelper.buildErrorResult("创建机构失败" + e.getMessage());
		}

		if (!org.equals("{}")) {
			try {
				// 创建pms机构信息
				com.sinosoft.framework.core.api.domain.OrganizationEntity organization = new com.sinosoft.framework.core.api.domain.OrganizationEntity();
				organization.setCode(organ.getOrgCode());
				organization.setName(organ.getOrgName());
				organization.setId(UUID.randomUUID().toString());
				organization.setCreatetime(new Date());
				organService.createOrganization(organization);
			} catch (BusinessException e) {
				organizationService.deleteOrganizationByOrgCode(organ.getOrgCode());
				organizationService.deleteDistrictByOrgCode(organ.getOrgCode());
				return ResultHelper.buildErrorResult("创建机构失败" + e.getMessage());
			}
		}
		return ResultHelper.buildSuccessResult(organ + id);
	}

	@Override
	public Map<String, Object> updateOrganization(OrganizationEntity organ) {

		return organizationService.updateOrganization(organ);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> updateOrganization(String organ, String district) {
		try {
			ObjectMapper om = new ObjectMapper();// 定义一个解析jsonMapper
			JsonNode organNode = om.readValue(organ, JsonNode.class);
			JsonNode disNode = om.readValue(district, JsonNode.class);
			String organization = organNode.path("organization").toString();// 获取机构信息集合
			String distr = disNode.path("district").toString();// 获取院区信息集合
			OrganizationEntity org = JSONObject.parseObject(organization, OrganizationEntity.class);// 获取机构信息
			Message message = PhaseInterceptorChain.getCurrentMessage();
			HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);// 获取到request
			org.setUpdateBy(Long.parseLong(request.getSession().getAttribute("username").toString()));
			organizationService.updateOrganization(org);
			List<DistrictEntity> districts = null;
			if (null != distr && !"".equals(distr) && !distr.equals("[{}]")) {
				districts = new ArrayList<DistrictEntity>();
				districts = JSONObject.parseArray(distr, DistrictEntity.class);
				for (DistrictEntity dis : districts) {
					organizationService.updateDistrict(dis);
				}
			}
		} catch (Exception e) {
			return ResultHelper.buildErrorResult("更新机构院区信息失败");
		}
		return ResultHelper.buildSuccessResult("更新成功");

	}

	@Override
	public Map<String, Object> retrieveOrganization(String orgName, String orgCode, String level, Integer currentPage,
			Integer rows) {
		if (null != orgCode && orgCode.equals("portal_app")) {
			orgCode = null;
		}
		PageList<OrganizationEntity> organs = organizationService.retrieveOrganization(orgName, orgCode, level,
				currentPage, rows);
		return ResultHelper.buildSuccessResult(organs);
	}

	@Override
	public Map<String, Object> updateOrganizationByOrgCode(Map<String, Object> map) {
		String orgCode = map.get("orgCode").toString();
		String status = map.get("status").toString();
		return organizationService.updateOrganizationByOrgCode(orgCode, status);
	}

	@Override
	public Map<String, Object> uploadPicture(InputStream is) {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = null;
		try {
			/*
			 * //定义一个jsonfactory MappingJsonFactory factory = new MappingJsonFactory();
			 * //解析固定的json格式的字符串 JsonParser parser = factory.createJsonParser(pictureInfo);
			 * //将json字符串转换为相应的Entity OrganizationEntity rr =
			 * parser.readValueAs(OrganizationEntity.class);
			 */
			bos = new ByteArrayOutputStream();
			while ((len = is.read(buffer)) != -1) {
				bos.write(buffer, 0, len);
			}
			bos.flush();
			bos.toByteArray();
			RequestResult files = weedfsService.uploadFiles(bos.toByteArray());
			return ResultHelper.buildSuccessResult(files.getFid());
		} catch (IOException e) {
			e.printStackTrace();
			return ResultHelper.buildErrorResult("图片上传失败" + e.getMessage());
		} finally {
			if (is == null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (bos == null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public Map<String, Object> updateSchoolDis(DistrictEntity schools) {
		return organizationService.updateDistrict(schools);
	}

	@Override
	public Map<String, Object> deleteSchoolDisById(String id) {
		return organizationService.deleteDistrictById(id);
	}

	@Override
	public Map<String, Object> deleteDistrictByOrgCodeAndDistrictId(String orgCode, String districtId) {
		try {
			organizationService.deleteDistrictByOrgCodeAndDistrictId(orgCode, districtId);
		} catch (Exception e) {
			return ResultHelper.buildErrorResult("删除院区失败");
		}
		return ResultHelper.buildSuccessResult("删除院区成功");
	}

	@Override
	public Map<String, Object> retrieveAppItemByDid(String did) {
		if (null == did || "".equals(did)) {
			return ResultHelper.buildErrorResult("请传入父id");
		}
		List<AppDictItemEntity> items = appDictService.retrieveItemByDid(did);
		return ResultHelper.buildSuccessResult(items);
	}

	@Override
	public Map<String, Object> retrieveAppItemByPcode(String pcode) {
		if (null == pcode || "".equals(pcode)) {
			return ResultHelper.buildErrorResult("请传入父编码");
		}
		List<AppDictItemEntity> items = appDictService.retrieveItemByPcode(pcode);
		return ResultHelper.buildSuccessResult(items);
	}

	public static void main(String[] args) throws JsonParseException, IOException {
		MappingJsonFactory factory = new MappingJsonFactory();
		// 解析固定的json格式的字符串
		String json = "{\"organ\":{\"orgName\":\"湖北省\",\"orgCode\":\"001\"},\"district\":{\"districtId\":"
				+ "\"0011\",\"districtName\":\"医院1\",\"orgCode\":\"001\"}}";
		JsonParser parser = factory.createJsonParser(json);
		// 将json字符串转换为相应的Entity
		JsonNode jsonNode = parser.readValueAsTree();
		JsonNode jsonNode2 = jsonNode.get("organ");
	}

	@Override
	public Map<String, Object> retrieveDist(String orgCode) {
		if(StringUtils.isBlank(orgCode)) {
			return ResultHelper.buildErrorResult("请稍后再试");
		}
		return organizationService.retrieveDistrictByOrgCode(orgCode);
	}

	@Override
	public Map<String, Object> retrieveAllOrg() {
		return organizationService.retrieveAllOrg();

	}

}
